package com.kantboot.system.user.user.service.impl;

import com.kantboot.system.user.user.domain.entity.SysUser;
import com.kantboot.system.user.user.domain.vo.LoginVO;
import com.kantboot.system.user.user.exception.UserAlreadyExistException;
import com.kantboot.system.user.user.service.ILoginService;
import com.kantboot.system.user.user.service.ISysUserService;
import com.kantboot.system.user.user.service.ISysUserTokenService;
import com.kantboot.util.common.password.KantbootPassword;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

    @Resource
    private KantbootPassword kantbootPassword;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysUserTokenService userTokenService;

    @Override
    public LoginVO registerWithUsernameAndPassword(String username, String password) {
        SysUser userByUsername = userService.getUserByUsername(username);
        if (userByUsername != null) {
            // 抛出用户已存在异常
            throw new UserAlreadyExistException();
        }
        SysUser user = new SysUser();
        user.setUsername(username);
        // 加密密码
        user.setPassword(kantbootPassword.encode(password));
        // 创建用户
        SysUser save = userService.createUser(user);
        // 生成token
        String token = userTokenService.generateToken(save.getId());
        return LoginVO.of(token,save);
    }

}